package com.ytjj.qmyx.users.controller;

import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.TokenConstants;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.users.model.request.WithdrawalRequest;
import com.ytjj.qmyx.users.service.LoginService;
import com.ytjj.qmyx.users.service.RedisService;
import com.ytjj.qmyx.users.service.UserWithdrawalRecordService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 提现控制器
 *
 *
 *  *
 **/
@RestController
@RequestMapping("/withdrawal")
public class UserWithdrawalRecordController extends BaseController {

    @Resource
    private UserWithdrawalRecordService userWithdrawalRecordService;

    @Resource
    private RedisService redisService;

    @Resource
    private LoginService loginService;
    /**
     * 添加用户提现
     */
    @PostMapping("/add")
    public CommonResult add(@Validated @RequestBody WithdrawalRequest request) {
        UsersResponse currentUser = getCurrentUser();
        if(null == currentUser || currentUser.getId() == null) {
            throw new ApiException("非法操作！");
        }

        request.setUserId(currentUser.getId());
        currentUser.setOpenid(request.getOpenid());

        loginService.saveOpenId(currentUser.getId(),request.getOpenid());
        redisService.set(TokenUtil.getToken(), JSONObject.toJSONString(currentUser));
        redisService.expire(TokenUtil.getToken(), TokenConstants.EXPIRE_SECONDS);

        userWithdrawalRecordService.add(request);
        return CommonResult.success();
    }

}
